﻿@model Xms.Web.Customize.Models.EditChartModel

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">
            <a data-toggle="collapse"
               href="#collapseTwo">
                <strong>@app.PrivilegeTree?.LastOrDefault().DisplayName</strong>
            </a>
        </h3>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse in">
        <div class="panel-body">
            <form action="/@app.OrganizationUniqueName/customize/chart/createchart" method="post" id="editform" class="form-horizontal" role="form">
                @Html.AntiForgeryToken()
                @Html.ValidationSummary()
                @Html.HiddenFor(x => x.EntityId)
                @Html.HiddenFor(x => x.SolutionId)
                @Html.HiddenFor(x => x.DataConfig)
                @Html.HiddenFor(x => x.PresentationConfig)
                <div class="form-group">
                    <label class="col-sm-2 control-label">实体</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control input-sm hide" id="entityselecter" />
                    </div>
                </div>
                <div class="form-group cc-form-ctrl">
                    <label class="col-sm-2 control-label">@app.T["chart_type"]</label>
                    <div class="col-sm-9">
                        <div class="btn-toolbar btn-group-lg" id="chartTypeSelector" role="toolbar" aria-label="">
                            <div class="btn-group" role="group" value="Bar" title="柱形图" aria-label="">
                                <span class="chart-bar"></span>
                            </div>
                            <div class="btn-group" role="group" value="HBar" title="条形图" aria-label="">
                                <span class="chart-HBar"></span>
                            </div>
                            <div class="btn-group" role="group" value="Line" title="折线图" aria-label="">
                                <span class="chart-Line"></span>
                            </div>
                            <div class="btn-group" role="group" value="Pie" title="饼图" aria-label="">
                                <span class="chart-Pie"></span>
                            </div>
                            <div class="btn-group" role="group" value="Funnel" title="漏斗图" aria-label="">
                                <span class="chart-Funnel"></span>
                            </div>
                            <div class="btn-group" role="group" value="Gauge" title="指标图" aria-label="">
                                <span class="chart-Gauge"></span>
                            </div>
                        </div>
                        <input type="hidden" name="chartType" id="chartType" value="0" class="required" />
                    </div>
                </div>
                <div class="form-group hide">
                    <label class="col-sm-2 control-label">@app.T["Preview_view"]</label>
                    <div class="col-sm-9">
                        <select class="form-control" id="ViewList">
                            <option value="-1">@app.T["please_select"]</option>
                        </select>
                    </div>
                </div>

                <div class="form-group row cc-form-ctrl">
                    @Html.LabelFor(x => x.Name, "名称", new { @class = "col-sm-2 control-label" })
                    <div class="col-sm-9">
                        @Html.TextBoxFor(x => x.Name, new { @class = "form-control required", @autofocus = true })
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <h4>@app.T["legend_entries"]</h4>
                    </div>
                </div>
                <div class="electrldom">
                    <div class="form-group electrldomItem cc-form-ctrl yarias-item">
                        <label class="control-label col-sm-2" for="title2">合计</label>
                        @*<div class="col-sm-4">
                                <input type="text" class="form-control required valid"  placeholder="序列名称" aria-required="true" />
                            </div>*@
                        <div class="col-sm-2">
                            <select class="form-control cc-selecter Attribute" name="Attribute">
                                @*<option value="-1">字段</option>*@
                            </select>
                        </div>
                        <div class="col-sm-2">
                            <select class="form-control cc-selecter" name="SeriesType">
                                @*<option value="-1">图形类型</option>*@
                                <option data-value="Bar" value="0">@app.T["chart_cylindricality"]</option>
                                <option data-value="HBar" value="1">@app.T["chart_bar_type"]</option>
                                <option data-value="Line" value="2">@app.T["chart_linear"]</option>
                                <option data-value="Pie" value="3">@app.T["pie_chart"]</option>
                                <option data-value="Funnel" value="4">@app.T["chart_funnel"]</option>
                                <option data-value="Gauge" value="5">指标图</option>
                            </select>
                        </div>
                        <div class="col-sm-2">
                            <select class="form-control cc-selecter" name="Aggregate">

                                <option data-type="other" data-value="count" value="4">@app.T["count_all"]</option>
                                <option data-type="int" data-value="sum" value="0">@app.T["total"]</option>
                                <option data-type="int" data-value="max" value="1">@app.T["maximum_value"]</option>
                                <option data-type="int" data-value="min" value="2">@app.T["minimum_value"]</option>
                                <option data-type="int" data-value="avg" value="3">@app.T["average_value"]</option>
                            </select>
                        </div>
                        <div class="col-sm-2">
                            <div class="dropdown-toggle">
                                <a class="btn" data-toggle="dropdown"><span class="glyphicon glyphicon-sort"></span></a>
                                <div class="dropdown-menu">
                                    <div class="btn-group xms-dropdown" role="group">
                                        <a class="btn"><span class="glyphicon glyphicon-sort-by-order"></span></a>
                                        <ul class="xms-dropdown-menu">
                                            <li data-dir="desc" data-count="3" onclick="createMethod.yaris.changeDirector(this)">@app.T["top_three_option"]</li>
                                            <li data-dir="desc" data-count="5" onclick="createMethod.yaris.changeDirector(this)">
                                                @app.T["top_five_option"]
                                                @*<a href="~/Views/Customize/CreateForm.cshtml">~/Views/Customize/CreateForm.cshtml</a>*@
                                            </li>
                                            <li class="customizeCount" data-dir="desc" onclick="createMethod.yaris.customizeCount(this)">@app.T["customize"]</li>
                                        </ul>
                                    </div>
                                    <div class="btn-group xms-dropdown" role="group">
                                        <a class="btn"><span class="glyphicon glyphicon-sort-by-order-alt"></span></a>
                                        <ul class="xms-dropdown-menu">
                                            <li data-dir="asc" data-count="3" onclick="createMethod.yaris.changeDirector(this)">底部3项</li>
                                            <li data-dir="asc" data-count="5" onclick="createMethod.yaris.changeDirector(this)">底部5项</li>
                                            <li class="customizeCount" data-dir="asc" onclick="createMethod.yaris.customizeCount(this)">@app.T["customize"]</li>
                                        </ul>
                                    </div>
                                    <div class="btn-group xms-dropdown" role="group">
                                        <a class="btn clearDirBtn" onclick="createMethod.yaris.clearDir(this);" title="清除排序数据"><span class="glyphicon glyphicon-remove"></span></a>
                                    </div>
                                </div>
                                <input type="hidden" name="TopCount" class="form-control valid number DirectorCount" data-dir="" value="0" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group row">
                    <div class="col-sm-2 col-sm-offset-2">
                        <span class="btn" id="addSeries"><em class="glyphicon glyphicon-plus"></em>添加条目</span>
                        <span class="btn hide" id="removeSeries"><em class="glyphicon glyphicon-minus"></em>@app.T["delete_series"]</span>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <h4>分组标签</h4>
                    </div>
                </div>
                <div class="form-group cc-form-ctrl xarias-item" id="xarias-item">
                    <label class="control-label col-sm-2" for="title2">分组</label>
                    <div class="col-sm-2">
                        <select id="HAttribute" name="Attribute" class="form-control">
                            @*<option value="">选择字段</option>*@
                        </select>
                    </div>
                    <div class="col-sm-2" style="display:none;">
                        <select class="form-control cc-selecter" name="dategrouping">
                            @*<option value="-1">日期分组</option>*@
                            <option data-value="year" value="0">@app.T["year"]</option>
                            <option data-value="month" value="1">@app.T["month"]</option>
                            <option data-value="day" value="2">@app.T["day"]</option>
                            <option data-value="quarter" value="3">@app.T["quarter"]</option>
                        </select>
                    </div>
                    <div class="col-sm-2">
                        <select class="form-control cc-selecter hide" name="groupby">
                            @*<option value="-1">分组</option>*@
                            <optgroup label="分组"></optgroup>
                            <option data-value="true" value="0">@app.T["yes"]</option>
                            <option data-value="false" value="1">@app.T["no"]</option>
                        </select>
                    </div>
                </div>

                <div class="form-group col-sm-3 col-sm-offset-2" id="form-buttons">
                    <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-saved"></span> @app.T["save"]</button>
                    <button type="reset" class="btn btn-default"><span class="glyphicon glyphicon-refresh"></span> @app.T["reset"]</button>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="customizeCountDialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">@app.T["define_top_Xitems"]</h4>
            </div>
            <div class="modal-body form-horizontal">
                <p class="modal-tags">@app.T["assign_define_top_Xitems"]</p>
                <div class="form-group row">
                    <label class="col-sm-3 control-label">@app.T["check_top_solution"]</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="director-count" data-dir="" value="0" />
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@app.T["cancel"]</button>
                <button type="button" class="btn btn-primary" onclick="createMethod.yaris.customizeCountSave()">@app.T["save"]</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

@section Scripts {
    <script src="/content/js/xms.metadata.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/form.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-validate/jquery.validate.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-validate/localization/messages_zh.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/chars.module.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery.tmpl.min.js?v=@app.PlatformSettings.VersionNumber"></script>

    <script>
        var chartData = new Xms.Form.ChartsParameters();
        var presentationData = new Xms.Form.PresentationParameters();
        var attributes = [];
        var entityid = $('#EntityId').val();
        var inttype = ['money', 'int', 'float'];
        function getAriasData() {
            $(".yarias-item").each(function () {
                var attribute = $(this).find(".Attribute").find('option:selected').attr('data-name');
                var type = 'series';
                var seriestype = $(this).find("select[name=SeriesType]").find('option:selected').attr('data-value');
                var aggregate = $(this).find("select[name=Aggregate]").find('option:selected').attr('data-value');
                var aggregateVal = $(this).find("select[name=Aggregate]").find('option:selected').val();
                var director = $(this).find("input.DirectorCount").attr("data-dir");
                var directorCount = $(this).find("input.DirectorCount").val();
                var aris = new Xms.Form.ChartsAxisParameters();
                aris.Attribute = attribute;
                aris.Type = type;
                aris.Aggregate = aggregate;
                aris.TopDirection = director == '' ? null : director;
                aris.TopCount = directorCount;
                if (aggregate.toLowerCase() == 'count' && aggregateVal == 5) {
                    aris.IgnoreNull = true
                } else {
                    aris.IgnoreNull = false;
                }
                chartData.Fetch.push(aris);
                var Series = {
                    'Name': attribute,
                    'Type': seriestype,
                    'ItemColor': '',
                    'Director': director,
                    'DirectorCount': directorCount
                };
                presentationData.Series.push(Series);
            });
            $(".xarias-item").each(function () {
                var attribute = $(this).find("#HAttribute").find('option:selected').attr('data-name');
                var dategrouping = $(this).find("select[name=dategrouping]").find('option:selected').attr('data-value');
                var groupby = $(this).find("select[name=groupby]").find('option:selected').attr('data-value');
                var type = 'category';
                var aris = new Xms.Form.ChartsAxisParameters();
                aris.Type = type;
                aris.Attribute = attribute;
                if ($(this).find('#HAttribute option:selected').attr('data-type') == 'datetime') {
                    aris.Dategrouping = dategrouping;
                }
                aris.Groupby = groupby;
                chartData.Fetch.push(aris);
            });

        }
         loadEntitys($('#entityselecter'));
        function loadEntitys($context,callback) {
            var entitySelect = $context;
            entitySelect.entitySelector({
                rendered: function (self) {
                    var _entityid = $('#EntityId').val();
                    if (_entityid) {
                        var acli = self.listWrap.find('.xms-autoc-item[value="' + _entityid + '"]');
                        if (acli.length > 0) {
                            self.box.val(_entityid);
                            self.listWrap.hide();
                            self.vInput.val(acli.text());
                            self.value = acli.attr('value');
                            self.wrap.attr('data-isactive', false);
                            self.filterData();
                        }
                    }
                },
                submithandler: function (self, $this) {
                    $('#EntityId').val(self.value);
                    loadAttributes(function () {

                    })
                },
                removehandler: function () {
                    $('#EntityId').val('00000000-0000-0000-0000-000000000000');
                    $('select[name=Attribute]').empty();
                     $('select[name=HAttribute]').empty();
                },
                inputPlaceHolder:'选择实体'
            });

        }
        function saveChartData() {
            chartData = new Xms.Form.ChartsParameters();
            presentationData = new Xms.Form.PresentationParameters();
            chartData.Type = $("#chartType").val();
            getAriasData();
            console.log(chartData);
            $('#PresentationConfig').val(JSON.stringify(presentationData));
            console.log($('#PresentationConfig').val())
            $('#DataConfig').val(JSON.stringify(chartData));
        }
        //加载字段
        function loadAttributes() {
            Xms.Schema.GetAttributes({ getall: true, entityid: $('#EntityId').val() }, function (data) {
                bindAttributes(data);
                //可添加删除插件
                $(".electrldom").ElementCtrl({
                    maxLength: 4,
                    addBtn: $("#addSeries"),
                    removeBtn: $("#removeSeries"),
                    ctrlClass: ".sItemDel"
                });
            });
        }
        function bindAttributes(items) {
            var _html = [];
            if (items && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    _html.push('<option data-name=' + items[i].name + ' data-type="' + items[i].attributetypename + '" value=' + items[i].attributeid + ' >' + items[i].localizedname + '</option>');
                }
                $('select[name=Attribute]').empty().append(_html.join(''));
                $('select[name=HAttribute]').empty().append(_html.join(''));
                $('select[name=Attribute]').trigger('change');
            }
        }
        var createMethod = {};
        createMethod.yaris = {};
        createMethod.yaris.customizeCount = function (obj) {
            var $this = $(obj), inputDialog = $("#customizeCountDialog"), director = $this.attr("data-dir"), modalInfo = {};
            $('.customizeCount').attr("data-active", "0");
            $this.attr("data-active", "1");
            $('#director-count').val($this.parents('.dropdown-toggle.open').find('.DirectorCount').val());
            if (typeof director == "string") {
                $("#director-count").attr("data-dir", director);
                if (director == "desc") {
                    modalInfo.title = "定义顶部 X 项";
                    modalInfo.tags = "指定要在图表中查看的 顶部 X 项数";
                    modalInfo.label = "查看 顶部 项目:";
                    setModalInfo();
                    inputDialog.modal("show");
                } else if (director == "asc") {
                    modalInfo.title = "定义底部 X 项";
                    modalInfo.tags = "指定要在图表中查看的 底部 X 项数";
                    modalInfo.label = "查看 底部 项目:";
                    setModalInfo();
                    inputDialog.modal("show");
                }
            }

            function setModalInfo() {
                inputDialog.find(".modal-title").text(modalInfo.title);
                inputDialog.find(".modal-tags").text(modalInfo.tags);
                inputDialog.find(".control-label").text(modalInfo.label);
            }
        }
        createMethod.yaris.customizeCountSave = function () {
            var $target = $(".customizeCount[data-active='1']"), inputDialog = $("#customizeCountDialog"), $obj = $("#director-count"), director = $obj.attr("data-dir");
            if ($target.length > 0) {
                var parent = $target.parents(".dropdown-toggle");
                parent.find("input.DirectorCount").attr("data-dir", director).val($obj.val());
                console.log(parent.find("input.DirectorCount").attr("data-dir"), parent.find("input.DirectorCount").val())
            }
            inputDialog.modal("hide");
            saveChartData();
        }
        createMethod.yaris.changeDirector = function (obj) {
            var $target = $(obj), director = $target.attr("data-dir"), dirCount = $target.attr("data-count");
            if ($target.length > 0) {
                var parent = $target.parents(".dropdown-toggle");
                parent.find("input.DirectorCount").attr("data-dir", director).val(dirCount);
                saveChartData();
                console.log(parent.find("input.DirectorCount").attr("data-dir"), parent.find("input.DirectorCount").val())
            }
        }
        createMethod.yaris.clearDir = function (obj) {
            var $target = $(obj), director = $target.attr("data-dir"), dirCount = $target.attr("data-count");
            if ($target.length > 0) {
                var parent = $target.parents(".dropdown-toggle");
                parent.find("input.DirectorCount").attr("data-dir", '').val(0);
                saveChartData();
                console.log(parent.find("input.DirectorCount").attr("data-dir"), parent.find("input.DirectorCount").val())
            }
        }

        $(function () {

            loadAttributes();
            //可添加删除插件
            $(".electrldom").ElementCtrl({
                maxLength: 4,
                addBtn: $("#addSeries"),
                removeBtn: $("#removeSeries"),
                ctrlClass: ".sItemDel"
            });
            $('body').on("change", "select", function () {
                if ($(this).prop('id') == 'HAttribute') {
                    if ($(this).find('option:selected').attr('data-type') == 'datetime') {
                        $('#xarias-item').find('select[name=dategrouping]').parent().show();
                    }
                    else {
                        $('#xarias-item').find('select[name=dategrouping]').parent().hide();
                    }
                }
                if ($(this).hasClass('Attribute') == true) {
                    if ($.inArray($(this).find('option:selected').attr('data-type'), inttype) != -1) {
                        $(this).parent().siblings().find('select[name=Aggregate] option[data-type="int"]').show();
                    }
                    else {
                        $(this).parent().siblings().find('select[name=Aggregate] option[value="-1"]').prop('selected', true);
                        $(this).parent().siblings().find('select[name=Aggregate] option[data-type="int"]').hide();
                    }
                }
                saveChartData();
            });
            $('input[type=text]').keyup(function () {
                saveChartData();
            });
            //表单验证
            Xms.Web.Form($("#editform"), function (response) {
                $("#chartTypeSelector .btn-group:eq(0)").click();
                $('#PresentationConfig').val('');
                $('#DataConfig').val('');
                Xms.Web.Alert(response.IsSuccess, response.Content);
                Xms.Web.Event.publish('refresh');
            });

            $(document.body).on("mouseenter", ".xms-dropdown", function () {
                var $this = $(this), target = $this.children(".xms-dropdown-menu");
                $this.addClass("xms-dropdown-open");
            }).on("mouseleave", ".xms-dropdown", function () {
                var $this = $(this), target = $this.siblings(".xms-dropdown-menu");
                $this.removeClass("xms-dropdown-open");
            });

            //图表类型选择
            $("#chartTypeSelector .btn-group").on("click", function () {
                var val = $(this).attr("value"), hidDom = $("#chartType");
                $(this)
                    .siblings(".btn-group")
                    .removeClass("active")
                    .end()
                    .addClass("active");
                hidDom.val(val);
                if (val == "Pie") {
                    $("select[name='SeriesType'] option").hide();
                    $("select[name='SeriesType'] option[value='3']").show();
                    $("select[name='SeriesType'] option[value='3']")
                        .prop("selected", true)
                        .prop("disabled", false);
                    $("#addSeries").hide();
                } else if (val == "Funnel") {
                    $("select[name='SeriesType'] option").hide();
                    $("select[name='SeriesType'] option[value='4']").show();
                    $("select[name='SeriesType'] option[value='4']")
                        .prop("selected", true)
                        .prop("disabled", false);
                    $("#addSeries").hide();
                } else if (val == 'Bar') {
                    $("select[name='SeriesType'] option").hide();
                    $("select[name='SeriesType'] option[value='0'],select[name='SeriesType'] option[value='2']").show();
                    $("select[name='SeriesType'] option[value='0']").prop('selected', true);
                }
                else if (val == 'HBar') {
                    $("select[name='SeriesType'] option").hide();
                    $("select[name='SeriesType'] option[value='1'],select[name='SeriesType'] option[value='2']").show();
                    $("select[name='SeriesType'] option[value='1']").prop('selected', true);
                } else if (val == 'Line') {
                    $("select[name='SeriesType'] option").hide();
                    $("select[name='SeriesType'] option[value='0'],select[name='SeriesType'] option[value='1'],select[name='SeriesType'] option[value='2']").show();
                    $("select[name='SeriesType'] option[value='2']").prop('selected', true);
                }
                else if (val == 'Gauge') {
                    $("select[name='SeriesType'] option").hide();
                    $("select[name='SeriesType'] option[value='5']").show();
                    $("select[name='SeriesType'] option[value='5']").prop('selected', true);
                    // $("#addSeries").show();
                }
                else {
                    $("select[name='SeriesType'] option[value='0']")
                        .prop("selected", true)
                        .prop("disabled", false);
                    $("#addSeries").show();
                }
                saveChartData();
            });

            $("#chartTypeSelector .btn-group:eq(0)").trigger('click');
        });
    </script>
}